package com.thread.chapter2;

import cn.hutool.core.thread.ThreadUtil;
import lombok.Data;

@Data
public class Demo234 extends Thread {
    private String execMethod = new String();

    public Demo234(String execMethod) {
        this.execMethod = execMethod;
    }

    public String getExecMethod() {
        return execMethod;
    }

    public void setExecMethod(String execMethod) {
        this.execMethod = execMethod;
    }

    volatile public static int countVolatile = 0;
    public static int count = 0;

    public static void addCountVolatile() {
        for (int i = 0; i < 100; i++) {
            countVolatile++;
        }
        System.out.println("countVolatile=" + countVolatile);
    }

    //一定要加static,这样synchronized锁的就是类了，达到同步效果
    public synchronized static void addCount() {
        for (int i = 0; i < 100; i++) {
            count++;
        }
        System.out.println("count=" + count);
    }

    @Override
    public void run() {
        super.run();

        if ("A".equals(execMethod)) {
            addCountVolatile();
        } else if ("B".equals(execMethod)) {
            addCount();
        }
    }

    public static void main(String[] args) {

        Demo234[] a = new Demo234[100];
        for (int i = 0; i < 100; i++) {
            a[i] = new Demo234("A");
        }
        for (int i = 0; i < 100; i++) {
//            a[i].start();
        }

        Demo234[] b = new Demo234[100];
        for (int i = 0; i < 100; i++) {
            a[i] = new Demo234("B");
        }
        for (int i = 0; i < 100; i++) {
            a[i].start();
        }

    }
}
